package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.controller.Response.R;
import com.itheima.pojo.Employee;
import com.itheima.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;
    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee){
        String password = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes());
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Employee::getUsername,employee.getUsername());
        Employee emp = employeeService.getOne(wrapper);
        if (emp==null){
            return R.error("用户名或密码错误");
        }
        if (!emp.getPassword().equals(password)){
            return R.error("用户名或密码错误");
        }
        if (emp.getStatus()==0){
            return R.error("改用户已被禁用");
        }
        request.getSession().setAttribute("employee",emp.getId());
        return R.success(emp);

    }
    @PostMapping("/logout")
    public R<String> loginOut(HttpServletRequest request){
        request.getSession().invalidate();
        return R.success("登陆退出成功");
    }
    @PostMapping
    public R<String> save(HttpServletRequest request,@RequestBody Employee employee){
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        employeeService.save(employee);
        return R.success("添加员工成功");
    }
    @GetMapping("/page")
    public R<Page> getPage(Integer page,Integer pageSize,String name){
        Page<Employee> pageinfo = new Page<>(page,pageSize);
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper();
        wrapper.like(!StringUtils.isEmpty(name),Employee::getName,name);
        wrapper.orderByDesc(Employee::getCreateTime);
        employeeService.page(pageinfo,wrapper);
        return R.success(pageinfo);
    }
    @PutMapping
    public R<String> updateStatus(HttpServletRequest request, @RequestBody Employee employee){
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getId,employee.getId());
        employeeService.update(employee,queryWrapper);
        return R.success("修改成功");
    }
    @GetMapping("/{id}")
    public R<Employee> updateEmplyee(@PathVariable Long id){
        Employee employee = employeeService.getById(id);
        return R.success(employee);
    }
}
